$(function() {

    var mdEditor = editormd("mdBody", {
        width: "80%",
        height: 740,
        path: '../../app/editormd/lib/',
        theme: "default",
        previewTheme: "default",
        editorTheme: "default",
        markdown: "",
        codeFold: true,
        saveHTMLToTextarea: true, // 保存 HTML 到 Textarea
        searchReplace: true,
        htmlDecode: "style,script,iframe|on*", // 开启 HTML 标签解析，为了安全性，默认不开启
        emoji: true,
        watch: true,
        taskList: true,
        tocm: false, // Using [TOCM]
        tex: true, // 开启科学公式TeX语言支持，默认关闭
        flowChart: true, // 开启流程图支持，默认关闭
        sequenceDiagram: true, // 开启时序/序列图支持，默认关闭,
        imageUpload: true,
        imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
        imageUploadURL: "/file/upload/mdImg",
        onload: function() {
            init();
        }
    });

    function init() {
        var href = window.location.href;
        var id = href.split('?')[1];
        $.get("/doc/update/get/" + id, function(data) {
            if (data && data.retCode == 0) {
                var doc = data.retVal;
                $("#docId").val(doc.id);
                $("#docName").val(doc.name);
                if (doc.tag) {
                    doc.tag.split(",").forEach(function(e, index) {
                        $("#docTag").tagsinput('add', e);
                    });
                }
                $("#description").val(doc.description);
                $(":radio[name=visibleRange]").each(function() {
                    if (this.value == doc.visibleRange) {
                        this.checked = true;
                    } else {
                        this.checked = false;
                    }
                });
                // 设置项目组可见信息
                if (2 == doc.visibleRange) {
                    $('#projectDiv').show();
                    if (doc.projects) {
                        doc.projects.forEach(function(e, index) {
                            $("#projectInput").tagsinput('add', {
                                'id': e.id,
                                'name': e.name
                            });
                        });
                    }
                }
                mdEditor.setMarkdown(doc.mdDetail);
            }
        });
    }



    $("#save").click(function() {
        var name = $("#docName").val();
        if (null == name || name.length == 0) {
            alert("文件名称不能为空。");
            return;
        }
        var docInfo = {
            "id": $("#docId").val(),
            "name": name,
            "tag": $("#docTag").val(),
            "description": $("#description").val(),
            "mdDetail": mdEditor.getMarkdown(),
            "htmlDetail": mdEditor.getHTML(),
            "visibleRange": $("input:checked[name=visibleRange]").val()
        };
        var projectIds = $("#projectInput").val();
        if (2 == docInfo.visibleRange) {
            if (null != projectIds && projectIds.length > 0) {
                docInfo["projectIds"] = projectIds;
            } else {
                alert("请选择项目");
                return;
            }
        }
        $.post("/doc/update", docInfo, function(data) {
            if (data.retCode == 0) {
                alert("更新成功");
            } else {
                alert("更新失败");
            }
        });
    });

    $("#showHide").click(function() {
        $("#mdBody").toggle();
        // mdEditor.hide();
        // mdEditor.show();
    });

    $("#previewHtml").click(function() {
        mdEditor.previewing();
    });

    $(":radio").click(function(event) {
        var val = this.value;
        $("#projectDiv").hide();
        if (val == 2) {
            $("#projectDiv").show();
        }
    });


    var projectBH = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        prefetch: {
            url: '/project/page?searchMap[name]=%QUERY',
            filter: function(data) {
                if (data && data.retCode == 0) {
                    var projects = new Array();
                    if (data.retVal.list) {
                        data.retVal.list.forEach(function(obj) {
                            projects.push({
                                'id': obj.id,
                                'name': obj.name
                            });
                        });
                        return projects;
                    }
                }
            }
        },
        remote: {
            url: '/project/page?searchMap[name]=%QUERY',
            wildcard: '%QUERY',
            filter: function(data) {
                if (data && data.retCode == 0) {
                    var projects = new Array();
                    if (data.retVal.list) {
                        data.retVal.list.forEach(function(obj) {
                            projects.push({
                                'id': obj.id,
                                'name': obj.name
                            });
                        });
                        return projects;
                    }
                }
            }
        }
    });

    projectBH.initialize();

    $("#projectInput").tagsinput({
        tagClass: function(item) {
            return (item.length > 10 ? 'big' : 'small') + ' label label-warning';
        },
        itemValue: 'id',
        itemText: 'name',
        freeInput: true,
        autoSelect: true,
        typeaheadjs: {
            classNames: { input: 'Typeahead-input' },
            name: 'projects',
            value: 'id',
            display: 'name',
            source: projectBH
        }
    });


});